package com.one.util;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @Description
 * @Author semstouch
 * @Date 2017/5/4
 **/
public class SMSWebChinese {
    protected static final Logger logger = LoggerFactory.getLogger(SMSWebChinese.class);

    public static void main(String[] args) {
        String Vcode=sendSMS("18650199186");
        ObjectMapper mapper = new ObjectMapper();
        Map oneUser = new HashMap();
        try {
            oneUser = mapper.readValue(Vcode, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(oneUser.get("code"));
        System.out.println(oneUser.get("obj"));
    }

    public static String sendSMS(String mobile){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/sms/sendcode.action";
        HttpPost httpPost = new HttpPost(url);

        String appKey = "ebf2037b77b3fed666c9a1b51dee3b96";
        String appSecret = "3cd386055f20";
        String nonce = "12345";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile",mobile));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);

            String res=EntityUtils.toString(response.getEntity(), "utf-8");
            ObjectMapper mapper = new ObjectMapper();
            Map resMap = new HashMap();
            try {
                resMap = mapper.readValue(res, Map.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(resMap.get("code").toString().equals("200")){
                return resMap.get("obj").toString();
            }
            logger.error("短信发送失败："+"手机号码为-"+mobile+"返回内容为"+res);
            return null;
            // 打印执行结果
        }catch (Exception e){
            logger.error("发送短信失败:"+e);
            return null;
        }

    }
}
